<?php

namespace App\Http\Controllers\Api;

use App\Model\User;
use App\Model\Wxapp;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller{
    //授权登录
    private $token;
    private $appId;
    private $appSecret;

    public function __construct(){
        $info=Wxapp::first();
        $this->appId=$info->app_id;
        $this->appSecret=$info->app_secret;
    }


    //登录
    public function login(Request $request){
        $post=$request->all();
        //微信登录 获取session_key
        $session = $this->wxlogin($post['code']);

        if (isset($session['code'])){
            return ['code'=>0,'msg'=>$session['msg']];
        }

        // 自动注册用户
        $user_id = $this->register($session['openid'], $post['nickName'],$post['avatarUrl'],$post['gender']);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid']);
        $session['user_id']=$user_id;
        // 记录缓存, 7天
        Cache::put($this->token,$session,86400*7);
        return ['code'=>1,'user_id'=>$user_id,'token'=>$this->getToken()];
    }


    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code){
        // 获取当前小程序信息
        if ($this->appId=="" || $this->appSecret=="") {
            return ['code'=>0,'msg'=>'请到[小程序-参数设置] 填写appid和appSecret'];
        }
        // 微信登录 (获取session_key)
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $url.= 'appid='.$this->appId.'&secret='.$this->appSecret.'&js_code='.$code.'&grant_type=authorization_code';
        $result = json_decode($this->get($url),true);

        if (isset($result['errcode'])) {
            return ['code' => 0, 'msg' => $result['errmsg']];;
        }

        return $result;
    }


    /**
     * 模拟GET请求 HTTPS的页面
     * @param string $url 请求地址
     * @return string $result
     */
    public function get($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid){
        return md5($openid . 'token_salt');
    }


    /**
     * 获取token
     * @return mixed
     */
    public function getToken(){
        return $this->token;
    }

    /**
     * 自动注册用户
     */
    private function register($open_id, $nickName,$avatarUrl,$gender){
        $userInfo['open_id'] = $open_id;
        $userInfo['nickName'] = preg_replace('/[\xf0-\xf7].{3}/', '', $nickName);
        $userInfo['avatarUrl'] = $avatarUrl;
        $userInfo['gender'] = $gender;

        $check=User::where('open_id',$open_id)->first();

        if(is_null($check)){
            $userInfo['create_time']=time();
            $user_id =DB::table('user')->insertGetId($userInfo);
            if (!$user_id) {
                return json_encode(['code'=>0,'msg' => '用户注册失败']);
            }
            return $user_id;
        }else{
            $userInfo['update_time']=time();
            DB::table('user')->where('user_id',$check->user_id)->update($userInfo);
            return $check->user_id;
        }
    }

}
